package fate.nsa;


import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class NSAReader {

    private byte[] buffer = new byte[256];
    private String encoding = System.getProperty("file.encoding");
    private ArrayList<NSAEntry> entries;

    public NSAReader(String path) throws IOException {
        ArrayList<NSAEntry> entries = new ArrayList<NSAEntry>();
        DataInputStream input = new DataInputStream(new BufferedInputStream(new FileInputStream(path)));
        try {
            int n = input.readShort();
            int global_offset = input.readInt();
            for (int i = 0; i < n; i++) {
                String name = readCString(input);
                input.skip(1);
                int offset = input.readInt();
                int size = input.readInt();
                int expandsize = input.readInt();
                entries.add(new NSAEntry(path, name, global_offset+offset, size, expandsize));
            }
        } finally {
            input.close();
        }
        this.entries = entries;
    }

    private String readCString(InputStream input) throws IOException {
        ByteArrayOutputStream name = new ByteArrayOutputStream();
        int x = input.read();
        while (x != 0) {
            if (x == -1) {
                throw new EOFException();
            }
            name.write(x);
            x = input.read();
        }
        return name.toString(encoding);
    }

    public List<NSAEntry> getEntries() {
        return entries;
    }

    public static void main(String[] args) throws IOException {
        NSAReader reader = new NSAReader("D:\\Projects\\Special\\libfate\\libfate-py\\arc1.nsa");
        long start = System.currentTimeMillis();
        for (NSAEntry entry: reader.getEntries()) {
            entry.read();
        }
        long end = System.currentTimeMillis();
        System.out.println(end-start);
    }
}
